<template>
	<cl-page>
		<view class="page">
			<!-- 页面头部 -->
			<view class="page-header">
				<view class="header-content">
					<text class="page-title">我的订单</text>
					<text class="page-subtitle">查看并管理您的所有订单</text>
				</view>
			</view>

			<!-- 搜索筛选区域 -->
			<cl-sticky>
				<view class="search-filter-section">
					<view class="search-box">
						<cl-search
							v-model="searchKeyword"
							placeholder="输入订单号或商品名称搜索"
							@search="handleSearch"
							@clear="handleSearch"
						/>
					</view>
					<view class="filter-actions">
						<view class="time-filter" @tap="showTimeFilter = true">
							<cl-icon name="calendar" size="14" color="#666"></cl-icon>
							<text class="filter-text">{{ getTimeRangeText() }}</text>
							<cl-icon name="arrow-down" size="10" color="#666"></cl-icon>
						</view>
					</view>
				</view>
			</cl-sticky>

			<!-- 订单列表 -->
			<view class="orders-list" v-if="!loading">
				<view class="order-item" v-for="order in filteredOrders" :key="order.id">
					<!-- 订单头部信息 -->
					<view class="order-header" :class="getOrderHeaderClass(order)">
						<view class="order-title">
							<cl-icon name="shopping-bag" size="14" color="#667eea"></cl-icon>
							<text
								class="title-text"
								:class="{ 'deleted-title': !canDeleteOrder(order) }"
							>
								{{ getOrderTitle(order) }}
							</text>
							<text v-if="!canDeleteOrder(order)" class="deleted-tag">已删除</text>
						</view>
						<view class="order-meta">
							<view class="meta-row">
								<view class="meta-item">
									<cl-icon name="document" size="12" color="#999"></cl-icon>
									<text class="order-number">订单号：{{ order.orderNum }}</text>
								</view>
								<view class="meta-item">
									<cl-icon name="time" size="12" color="#999"></cl-icon>
									<text class="order-time">{{
										formatOrderTime(order.createTime)
									}}</text>
								</view>
							</view>
							<!-- 订单状态（remark） -->
							<view v-if="order.remark" class="order-remark">
								<view class="remark-tag" :class="getRemarkClass(order.remark)">
									<cl-icon
										:name="getRemarkIcon(order.remark)"
										size="12"
									></cl-icon>
									<text>{{ order.remark }}</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 订单商品列表 -->
					<view class="order-products">
						<view
							class="product-item"
							v-for="product in order.goodsList"
							:key="product.id"
							:class="{ 'deleted-product': product.deleteStatus === 1 }"
						>
							<view class="product-image">
								<cl-image
									:src="product.goodsInfo?.mainPic || '/static/icon/no-image.png'"
									:size="[80, 80]"
									:radius="8"
									mode="aspectFill"
									@error="handleImageError"
								/>
							</view>

							<view class="product-info">
								<text class="product-name">{{ product.goodsInfo?.title }}</text>
								<text class="product-spec">{{ product.goodsInfo?.goodsSpec }}</text>
								<view class="product-meta">
									<text class="manufacturer">{{
										product.goodsInfo?.manufacturer
									}}</text>
									<text class="quantity">x{{ product.count }}</text>
								</view>
							</view>

							<view class="product-price">
								<text class="price-value">{{
									formatUserPrice(
										order.title === "近效期订单"
											? product.goodsInfo.nextValPrice
											: product.price || 0,
										user,
										order.remark === "秒杀订单"
											? 1
											: product.goodsInfo?.noDiscounts
									)
								}}</text>
								<text
									v-if="
										product.discountPrice &&
										product.discountPrice !== '0.00' &&
										order.remark !== '秒杀订单'
									"
									class="discount-price"
								>
									优惠{{ formatPrice(product.discountPrice) }}
								</text>
							</view>

							<view
								class="product-actions"
								v-if="
									order.goodsList &&
									order.goodsList.length > 1 &&
									canDeleteProduct(product)
								"
							>
								<view
									class="delete-btn"
									@tap.stop="
										handleDeleteProduct(
											order.orderNum,
											product.goodsInfo?.goodsId
										)
									"
								>
									<cl-icon name="delete" size="12" color="#ff4444"></cl-icon>
								</view>
							</view>
						</view>
					</view>

					<!-- 订单底部信息 -->
					<view class="order-footer">
						<view class="order-summary">
							<view class="summary-info">
								<text class="total-label"
									>共{{ getTotalQuantity(order) }}件商品</text
								>
								<text class="total-amount">{{
									formatUserPrice(
										calculateOrderTotal(order),
										user,
										order.remark === "秒杀订单" ? 1 : 0
									)
								}}</text>
							</view>
						</view>

						<view class="order-actions">
							<view
								v-if="canDeleteOrder(order)"
								class="action-btn danger"
								@tap.stop="handleDeleteOrder(order.orderNum)"
							>
								<cl-icon name="delete" size="12" color="#ff4444"></cl-icon>
								<text class="btn-text">删除</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<cl-empty
					v-if="filteredOrders.length === 0 && !loading"
					icon="order"
					text="暂无相关订单"
					:margin="[80, 0, 0, 0]"
				>
					<template #extra>
						<cl-button type="primary" size="small" @tap="goShopping">去购物</cl-button>
					</template>
				</cl-empty>

				<!-- 加载状态 -->
				<view v-if="loading" class="loading-state">
					<cl-loading />
					<text class="loading-text">加载中...</text>
				</view>
			</view>
		</view>

		<!-- 时间筛选弹窗 -->
		<cl-popup v-model="showTimeFilter" direction="bottom" :height="300">
			<view class="time-filter-modal">
				<view class="modal-header">
					<text class="modal-title">选择时间范围</text>
					<cl-icon
						name="close"
						size="18"
						color="#666"
						@tap="showTimeFilter = false"
					></cl-icon>
				</view>
				<view class="modal-content">
					<view
						class="time-option"
						v-for="option in timeOptions"
						:key="option.value"
						:class="{ active: timeRange === option.value }"
						@tap="selectTimeRange(option.value)"
					>
						<text class="option-text">{{ option.label }}</text>
						<cl-icon
							v-if="timeRange === option.value"
							name="check"
							size="14"
							color="#667eea"
						></cl-icon>
					</view>
				</view>
			</view>
		</cl-popup>
	</cl-page>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { onReady, onShow } from "@dcloudio/uni-app";
import { useCool } from "/@/cool";
import { useUi } from "/$/cool-ui";
import { useStore } from "/@/cool/store";
import { formatUserPrice } from "/@/utils/price";

const { user } = useStore();
const { service, router } = useCool();
const ui = useUi();

// 页面状态
const loading = ref(false);
const searchKeyword = ref("");
const timeRange = ref("3months");
const showTimeFilter = ref(false);
const list = ref<OrderInfo[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 时间筛选选项
const timeOptions = [
	{ label: "最近三个月", value: "3months" },
	{ label: "今年内", value: "thisYear" },
	{ label: "去年", value: "lastYear" },
	{ label: "全部时间", value: "all" },
];

// 获取时间范围文本
function getTimeRangeText() {
	const option = timeOptions.find((opt) => opt.value === timeRange.value);
	return option ? option.label : "选择时间";
}

// 选择时间范围
async function selectTimeRange(value: string) {
	timeRange.value = value;
	showTimeFilter.value = false;
	await refresh({ page: 1 });
}

// 筛选后的订单列表
const filteredOrders = computed(() => {
	let result = [...list.value];

	// 按关键词搜索
	if (searchKeyword.value) {
		const keyword = searchKeyword.value.toLowerCase();
		result = result.filter(
			(order) =>
				order.orderNum?.toLowerCase().includes(keyword) ||
				order.goodsList?.some((p) => p.goodsInfo?.title?.toLowerCase().includes(keyword))
		);
	}

	return result;
});

// 获取订单列表
async function refresh(params?: any) {
	console.log("refresh 函数被调用, 参数:", params);
	loading.value = true;
	try {
		const pageParams = {
			page: params?.page || currentPage.value,
			size: params?.size || pageSize.value,
		};

		console.log("请求订单列表参数:", pageParams);
		const res = await service.order.info.page(pageParams);
		console.log("订单列表响应:", res);

		if (res && res.list) {
			list.value = res.list;
			total.value = res.pagination?.total || 0;
			console.log(`获取到 ${list.value.length} 个订单`);

			// 处理订单数据，确保商品信息存在
			list.value.forEach((order) => {
				if (order.goodsList) {
					order.goodsList.forEach((product) => {
						if (!product.goodsInfo) {
							product.goodsInfo = {} as any;
						}
					});
				}
			});
		} else {
			console.warn("未获取到订单列表数据");
		}
	} catch (error) {
		console.error("刷新订单列表失败:", error);
		ui.showToast("加载订单失败");
	} finally {
		loading.value = false;
		console.log("refresh 函数执行完成");
	}
}

// 搜索处理
async function handleSearch() {
	await refresh({ page: 1 });
}

// 去购物
function goShopping() {
	router.push("/pages/index/home");
}

// 生成订单标题
function getOrderTitle(order: OrderInfo): string {
	if (!order.goodsList || order.goodsList.length === 0) return "订单详情";

	if (order.goodsList.length === 1) {
		return order.goodsList[0].goodsInfo?.title || "订单详情";
	} else {
		return `${order.goodsList[0].goodsInfo?.title} 等${order.goodsList.length}件商品`;
	}
}

// 格式化订单时间
function formatOrderTime(timeString: string | Date | undefined): string {
	if (!timeString) return "";

	// Handle iOS date format compatibility
	let date: Date;
	if (typeof timeString === "string") {
		// Convert "yyyy-MM-dd HH:mm:ss" to "yyyy/MM/dd HH:mm:ss" for iOS compatibility
		const formattedTimeString = timeString.replace(/-/g, "/");
		date = new Date(formattedTimeString);
	} else {
		date = new Date(timeString);
	}

	// Add 8 hours for timezone adjustment
	date.setHours(date.getHours() + 8);
	return date.toLocaleString("zh-CN", {
		month: "2-digit",
		day: "2-digit",
		hour: "2-digit",
		minute: "2-digit",
	});
}

// 格式化价格
function formatPrice(price: number | string | undefined): string {
	if (price === undefined || price === null) return "¥0.00";
	const numPrice = Number(price);
	return `¥${numPrice.toFixed(2)}`;
}

// 计算订单总价
function calculateOrderTotal(order: OrderInfo): number {
	if (!order.goodsList) return 0;
	return order.goodsList.reduce((total, product) => {
		const price =
			order.title === "近效期订单"
				? Number(product.goodsInfo.nextValPrice || 0)
				: Number(product.price || 0);
		const count = product.count || 0;
		return total + price * count;
	}, 0);
}

// 获取总数量
function getTotalQuantity(order: OrderInfo): number {
	if (!order.goodsList) return 0;
	return order.goodsList.reduce((total, product) => total + (product.count || 0), 0);
}

// 判断是否可以删除订单
function canDeleteOrder(order: OrderInfo): boolean {
	if (!order.goodsList) return false;
	return order.goodsList.some((p) => p.deleteStatus === 0);
}

// 判断是否可以删除商品
function canDeleteProduct(product: OrderGoods): boolean {
	return product.deleteStatus === 0;
}

// 获取订单头部样式类
function getOrderHeaderClass(order: any): string {
	if (!canDeleteOrder(order)) return "header-deleted";
	if (order.remark === "已开票") return "header-invoiced";
	if (order.remark === "已出库") return "header-shipped";
	return "";
}

// 获取备注标签样式类
function getRemarkClass(remark: string): string {
	if (remark === "已开票") return "remark-invoiced";
	if (remark === "已出库") return "remark-shipped";
	return "remark-default";
}

// 获取备注图标
function getRemarkIcon(remark: string): string {
	if (remark === "已开票") return "check";
	if (remark === "已出库") return "box";
	return "info-o";
}

// 处理图片错误
function handleImageError() {
	// 图片加载失败时的处理
}

// 删除订单中的商品
async function handleDeleteProduct(orderNum: any, goodsId: any) {
	try {
		const result = await uni.showModal({
			title: "删除商品",
			content: "确定要删除这个商品吗？删除后将无法恢复",
			confirmText: "确定",
			cancelText: "取消",
			confirmColor: "#ff4444",
		});

		if (!result.confirm) return;

		console.log("删除商品请求参数:", { orderNum, goodsId });

		// 调用删除商品API
		const response = await service.order.info.deleteOrderGoods({
			orderNum,
			goodsId,
		});

		await refresh();
	} catch (err: any) {
		console.error("删除商品失败:", err);
		uni.showToast({ title: err.message || "删除商品失败", icon: "error" });
	}
}

// 删除整个订单
async function handleDeleteOrder(orderNum: any) {
	try {
		const result = await uni.showModal({
			title: "删除订单",
			content: "确定要删除这个订单吗？删除后将无法恢复",
			confirmText: "确定",
			cancelText: "取消",
			confirmColor: "#ff4444",
		});

		if (!result.confirm) return;

		console.log("删除订单请求参数:", { orderNum });

		// 调用删除订单API
		const response = await service.order.info.deleteOrder({
			orderNum,
		});

		await refresh();
	} catch (err: any) {
		console.error("删除订单失败:", err);
		uni.showToast({ title: err.message || "删除订单失败", icon: "error" });
	}
}

onReady(async () => {
	await refresh();
});

onShow(async () => {
	if (ui.loaded) {
		await refresh({});
	}
});

defineExpose({
	refresh,
});
</script>

<style lang="scss" scoped>
.page {
	background-color: #f8f9fa;
	min-height: 100vh;
}

.page-header {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 32rpx 24rpx 24rpx;

	.header-content {
		.page-title {
			display: block;
			font-size: 40rpx;
			font-weight: bold;
			color: #fff;
			margin-bottom: 8rpx;
		}

		.page-subtitle {
			display: block;
			font-size: 24rpx;
			color: rgba(255, 255, 255, 0.8);
		}
	}
}

.search-filter-section {
	background-color: #fff;
	padding: 20rpx 24rpx;
	border-bottom: 1rpx solid #f0f0f0;

	.search-box {
		margin-bottom: 16rpx;
	}

	.filter-actions {
		.time-filter {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 12rpx 20rpx;
			background-color: #f8f9fa;
			border-radius: 20rpx;
			border: 1rpx solid #e9ecef;

			.filter-text {
				font-size: 24rpx;
				color: #666;
				margin: 0 12rpx;
			}
		}
	}
}

.orders-list {
	padding: 16rpx;
}

.order-item {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 16rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
	border: 1rpx solid #f0f0f0;
	transition: all 0.3s ease;

	&:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}
}

.order-header {
	padding: 20rpx 24rpx 16rpx;
	border-bottom: 1rpx solid #f8f9fa;
	background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%);
	position: relative;
	transition: all 0.3s ease;

	&.header-invoiced {
		background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%);
		border-bottom: 2rpx solid #67c23a;

		&::after {
			content: "✓ 已开票";
			position: absolute;
			top: 16rpx;
			right: 24rpx;
			background: #67c23a;
			color: white;
			padding: 8rpx 16rpx;
			border-radius: 24rpx;
			font-size: 24rpx;
			font-weight: 500;
			box-shadow: 0 4rpx 8rpx rgba(103, 194, 58, 0.3);
		}
	}

	&.header-shipped {
		background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%);
		border-bottom: 2rpx solid #409eff;

		&::after {
			content: "📦 已出库";
			position: absolute;
			top: 16rpx;
			right: 24rpx;
			background: #409eff;
			color: white;
			padding: 8rpx 16rpx;
			border-radius: 24rpx;
			font-size: 24rpx;
			font-weight: 500;
			box-shadow: 0 4rpx 8rpx rgba(64, 158, 255, 0.3);
		}
	}

	&.header-deleted {
		background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
		border-bottom: 2rpx solid #ef4444;
		opacity: 0.7;
	}

	.order-title {
		display: flex;
		align-items: center;
		margin-bottom: 8rpx;

		.title-text {
			font-size: 28rpx;
			font-weight: 600;
			color: #333;
			margin-left: 12rpx;
			flex: 1;
			line-height: 1.3;

			&.deleted-title {
				text-decoration: line-through;
				color: #999;
			}
		}

		.deleted-tag {
			font-size: 20rpx;
			color: #ff4444;
			background-color: #fff5f5;
			padding: 4rpx 8rpx;
			border-radius: 8rpx;
			margin-left: 12rpx;
		}
	}

	.order-meta {
		.meta-row {
			display: flex;
			flex-wrap: wrap;
			gap: 24rpx;
			margin-top: 12rpx;
		}

		.meta-item {
			display: flex;
			align-items: center;
			gap: 8rpx;
		}

		.order-number {
			font-size: 24rpx;
			color: #666;
		}

		.order-time {
			font-size: 24rpx;
			color: #666;
		}

		.order-remark {
			margin-top: 12rpx;
		}

		.remark-tag {
			display: inline-flex;
			align-items: center;
			gap: 8rpx;
			padding: 8rpx 16rpx;
			border-radius: 24rpx;
			font-size: 24rpx;
			font-weight: 500;

			&.remark-invoiced {
				background: #f0f9eb;
				border: 1rpx solid #e1f3d8;
				color: #67c23a;
			}

			&.remark-shipped {
				background: #ecf5ff;
				border: 1rpx solid #d9ecff;
				color: #409eff;
			}

			&.remark-default {
				background: #f4f4f5;
				border: 1rpx solid #e9e9eb;
				color: #909399;
			}
		}
	}
}

.order-products {
	.product-item {
		display: flex;
		padding: 16rpx 24rpx;
		border-bottom: 1rpx solid #f8f9fa;
		position: relative;
		transition: all 0.2s ease;

		&:last-child {
			border-bottom: none;
		}

		&.deleted-product {
			background-color: #fef2f2;
			border-left: 4rpx solid #ef4444;
			opacity: 0.8;

			.product-name {
				text-decoration: line-through;
				color: #999;
			}

			.product-image {
				position: relative;

				&::after {
					content: "已删除";
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
					background: rgba(239, 68, 68, 0.9);
					color: white;
					font-size: 20rpx;
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
					font-weight: 600;
				}
			}
		}
	}

	.product-image {
		margin-right: 16rpx;
		flex-shrink: 0;
	}

	.product-info {
		flex: 1;
		min-width: 0;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.product-name {
			font-size: 26rpx;
			font-weight: 500;
			color: #333;
			line-height: 1.3;
			margin-bottom: 4rpx;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			line-clamp: 2;
			-webkit-box-orient: vertical;
			overflow: hidden;
		}

		.product-spec {
			font-size: 22rpx;
			color: #666;
			margin-bottom: 8rpx;
		}

		.product-meta {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.manufacturer {
				font-size: 20rpx;
				color: #999;
				flex: 1;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}

			.quantity {
				font-size: 22rpx;
				color: #666;
				margin-left: 8rpx;
			}
		}
	}

	.product-price {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: space-between;
		margin-left: 16rpx;
		min-width: 80rpx;

		.price-value {
			font-size: 26rpx;
			font-weight: 600;
			color: #ff4444;
			text-align: right;
		}

		.discount-price {
			font-size: 20rpx;
			color: #52c41a;
			text-align: right;
		}
	}

	.product-actions {
		.delete-btn {
			position: absolute;
			top: 8rpx;
			right: 8rpx;
			width: 32rpx;
			height: 32rpx;
			background-color: #fff5f5;
			border: 1rpx solid #ffccc7;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}

.order-footer {
	padding: 16rpx 24rpx 20rpx;
	background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%);
	border-top: 1rpx solid #f0f0f0;

	.order-summary {
		margin-bottom: 16rpx;

		.summary-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 4rpx;
		}

		.total-label {
			font-size: 24rpx;
			color: #666;
		}

		.total-amount {
			font-size: 28rpx;
			font-weight: bold;
			color: #ff4444;
		}

		.discount-info {
			font-size: 20rpx;
			color: #52c41a;
			text-align: right;
		}
	}

	.order-actions {
		display: flex;
		gap: 12rpx;
		justify-content: flex-end;

		.action-btn {
			display: flex;
			align-items: center;
			padding: 8rpx 16rpx;
			border-radius: 16rpx;
			border: 1rpx solid;

			&.danger {
				background-color: #fff5f5;
				border-color: #ffccc7;

				.btn-text {
					color: #ff4444;
					margin-left: 6rpx;
					font-size: 22rpx;
				}
			}

			&.primary {
				background-color: #f0f8ff;
				border-color: #b3d8ff;

				.btn-text {
					color: #667eea;
					margin-left: 6rpx;
					font-size: 22rpx;
				}
			}
		}
	}
}

.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80rpx 0;

	.loading-text {
		font-size: 24rpx;
		color: #999;
		margin-top: 16rpx;
	}
}

.time-filter-modal {
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.modal-title {
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.modal-content {
		padding: 24rpx;

		.time-option {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f0f0f0;

			&:last-child {
				border-bottom: none;
			}

			&.active {
				.option-text {
					color: #667eea;
					font-weight: 500;
				}
			}

			.option-text {
				font-size: 26rpx;
				color: #333;
			}
		}
	}
}
</style>
